package com.lzy.utils;

import com.lzy.entity.SysMenuEntity;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 树形工具类
 *
 * @author lyw
 * @Date 2023/3/10-下午5:31
 */
public class TreeUtil{

  /**
   * 用来重构菜单的接口
   *
   * @param menus 所有菜单信息
   * @return  结果
   */
  public static List<SysMenuEntity> screening(List<SysMenuEntity> menus) {
    List<SysMenuEntity> result = new ArrayList<>();
    Map<Long, List<SysMenuEntity>> menuMap = menus.stream().collect(Collectors.groupingBy(SysMenuEntity::getParentId));

    List<Long> parentIds = new ArrayList<>(menuMap.keySet());
    Collections.sort(parentIds);

    // 封装子集菜单
    for (Long parentId : parentIds) {
      List<SysMenuEntity> menuEntities = menuMap.get(parentId);
      for (SysMenuEntity menuEntity : menuEntities) {
        List<SysMenuEntity> children = menuMap.get(menuEntity.getMenuId());
        menuEntity.setChildren(children);
        result.add(menuEntity);
      }
    }

    return menuMap.get(parentIds.get(0));
  }
}
